/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Usuario;

import Model.User;
import com.google.gson.Gson;
import java.util.ArrayList;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;

/**
 *
 * @author Radek
 */
@Path("/cadastroUsuario")
public class CadastroUsuario {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public Response cadastroUsuario(User user) {

        Session session = null;
        String resultado;
        try {
            session = HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
            resultado = "OK";
        } 
        catch (ConstraintViolationException b) {
            System.out.println(b);
            resultado = "Error";
            session.getTransaction().rollback();
        }
        catch (Exception e) {
            System.out.println(e);
            resultado = "Error";
            session.getTransaction().rollback();
        }
        finally {
            try {
                HibernateUtil.closeSession();
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }
        // HibernateUtil.getSessionFactory().close();
        return Response.status(201).entity(resultado).build();
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getCoordenates() {
        Session session = null;
        String resultado;
        try {
            session = HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            User user = new User();
            ArrayList<User> registro = (ArrayList<User>) session.createQuery("From User").list();
            HibernateUtil.commitTransaction();
            Gson gson = new Gson();
            resultado = gson.toJson(registro);
        } catch (Exception e) {
            System.out.println(e);
            resultado = "Error";
            session.getTransaction().rollback();
        } finally {
            try {
                HibernateUtil.closeSession();
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }

        return resultado;
    }
}
